<!--
 * @Author: 李天惊 uf_lee@163.com
 * @Date: 2025-02-10 11:35:53
 * @LastEditors: 李天惊 uf_lee@163.com
 * @LastEditTime: 2025-03-18 17:38:30
 * @FilePath: \global-brain\global-brain-admin\src\views\System\Knowledge\Index.vue
 * Copyright (c) 2025 by ${git_name_email}, All Rights Reserved. 
-->
<script setup lang="ts">
import {
  ref,
  // unref,
  reactive
} from 'vue'
import { ElButton, ElMessageBox } from 'element-plus'
import { ContentWrap } from '@/components/ContentWrap'
import { Search } from '@/components/Search'
import { Table } from '@/components/Table'
// import Edit from './components/Edit.vue'
// import See from './components/See.vue'
import { useTable } from '@/hooks/web/useTableTest'
import { useI18n } from '@/hooks/web/useI18n'
import { CrudSchema, useCrudSchemas } from '@/hooks/web/useCrudSchemas'
import { useIcon } from '@/hooks/web/useIcon'
import {
  // sysKnowledgeAddApi,
  sysKnowledgeBatchDelApi,
  sysKnowledgeDelApi,
  // sysKnowledgeEditApi,
  sysKnowledgeListApi
} from '@/api/sys/knowledge'
import { sysKnowledgeClassListApi } from '@/api/sys/knowledgeClass'
// 获取字典
import { getDictLabel } from '@/utils/lee'
import { useCache } from '@/hooks/web/useCache'
const { wsCache } = useCache()
const dict: any = wsCache.get('dict')

const { t } = useI18n()
const loading = ref(false) // 是否加载中
const dialogVisible = ref(false) // 弹窗显示
const dialogTitle = ref('') // 弹窗标题
const actionType = ref('') // 操作类型
const delLoading = ref(false) // 删除loading
const iconEdit = useIcon({ icon: 'ep:edit' })
const iconSee = useIcon({ icon: 'ep:view' })
const iconDel = useIcon({ icon: 'ep:delete' })

const { register, tableObject, methods } = useTable<
  {
    total: number
    list: any[]
  },
  any
>({
  getListApi: sysKnowledgeListApi,
  response: {
    data: 'data',
    count: 'count'
  }
})

const { getList, setSearchParams, getSelections } = methods

const classData = ref([])
// 分类列表查询
const getClassList = async () => {
  let res = await sysKnowledgeClassListApi({})
    .catch(() => {})
    .finally(() => {
      loading.value = false
    })
  if (res) {
    classData.value = res.data
  }
}

const crudSchemas = reactive<CrudSchema[]>([
  {
    field: 'knowledge_id',
    label: '主键',
    fixed: 'left',
    width: 60,
    table: {
      show: true
    },
    form: {
      show: false
    },
    detail: {
      show: false
    }
  },
  {
    field: 'title',
    label: '标题',
    search: {
      show: true
    }
  },
  {
    field: 'type',
    label: '类型',
    width: 80,
    formatter: (_: Recordable, __: TableColumn, cellValue: number | string) => {
      return getDictLabel(dict, 'sys_knowledge_type', cellValue)
    },
    form: {
      component: 'Select',
      componentProps: {
        options: dict.sys_knowledge_type
      }
    },
    search: {
      component: 'Select',
      componentProps: {
        options: dict.sys_knowledge_type
      },
      show: true
    }
  },
  {
    field: 'knowledge_class_id',
    label: '知识库分类',
    table: {
      show: false
    },
    search: {
      component: 'TreeSelect',
      componentProps: {
        data: classData,
        'check-strictly': true,
        'default-expand-all': true,
        'node-key': 'knowledge_class_id',
        props: {
          children: 'children',
          label: 'class_name'
        }
      },
      show: true
    },
    form: {
      component: 'TreeSelect',
      componentProps: {
        data: classData,
        'check-strictly': true,
        'default-expand-all': true,
        'node-key': 'knowledge_class_id',
        props: {
          children: 'children',
          label: 'class_name'
        }
      },
      show: true
    },
    detail: {
      show: false
    }
  },
  {
    field: 'class_name',
    label: '知识库分类',
    search: {
      show: false
    },
    form: {
      show: false
    }
  },
  {
    field: 'action',
    width: 300,
    label: t('tableDemo.action'),
    form: {
      show: false
    },
    detail: {
      show: false
    }
  }
])

const { allSchemas } = useCrudSchemas(crudSchemas)

const action = async (type: string, row: any = {}) => {
  actionType.value = type
  switch (type) {
    case 'edit':
      dialogTitle.value = '编辑'
      tableObject.currentRow = row
      dialogVisible.value = true
      break
    case 'add':
      dialogTitle.value = '新增'
      tableObject.currentRow = {}
      dialogVisible.value = true
      break
    case 'see':
      dialogTitle.value = '查看'
      tableObject.currentRow = row
      dialogVisible.value = true
      break
    case 'del':
      ElMessageBox.confirm('确定要删除这个角色吗？', '删除', {
        confirmButtonText: '确认',
        cancelButtonText: '取消',
        type: 'warning'
      })
        .then(() => {
          apiDel(row.knowledge_id)
        })
        .catch(() => {
          console.log('这里是取消confirm弹框')
        })
      break
    case 'batchDel':
      ElMessageBox.confirm(t('common.delMessage'), t('common.delWarning'), {
        confirmButtonText: t('common.delOk'),
        cancelButtonText: t('common.delCancel'),
        type: 'warning'
      })
        .then(async () => {
          delLoading.value = true
          const selections = await getSelections()
          const ids = selections.map((v) => v.tag_group_id)
          let res = await sysKnowledgeBatchDelApi({ ids: ids.join(',') })
            .catch(() => {})
            .finally(() => {
              delLoading.value = false
            })
          if (res) {
            getList()
          }
        })
        .catch(() => {})
    default:
      console.log('未知类型')
  }
}

/**
 * 删除
 * @param knowledge_id
 * @returns
 */

const apiDel = async (knowledge_id) => {
  let delRes = await sysKnowledgeDelApi({ knowledge_id: knowledge_id })
    .catch(() => {})
    .finally(() => {
      loading.value = false
    })
  if (delRes) {
    getList()
  }
}

//初始化
const init = async () => {
  // 查询知识库分类数据
  getClassList()
  // 查询列表
  await getList()
}
init()
</script>

<template>
  <ContentWrap>
    <Search :schema="allSchemas.searchSchema" @search="setSearchParams" @reset="setSearchParams" />
    <div class="mb-10px">
      <ElButton type="primary" @click="action('add')">新增</ElButton>
      <ElButton :loading="delLoading" type="danger" @click="action('batchDel')">
        批量删除
      </ElButton>
    </div>

    <Table
      v-model:pageSize="tableObject.pageSize"
      v-model:currentPage="tableObject.currentPage"
      :columns="allSchemas.tableColumns"
      :data="tableObject.tableList"
      :loading="tableObject.loading"
      :border="true"
      :pagination="{
        total: tableObject.count
      }"
      @register="register"
    >
      <template #action="{ row }">
        <ElButton type="primary" :icon="iconEdit" @click="action('edit', row)" title="编辑">
          编辑
        </ElButton>
        <ElButton type="success" :icon="iconSee" @click="action('see', row)" title="详情">
          详情
        </ElButton>
        <ElButton type="danger" :icon="iconDel" @click="action('del', row)" title="删除">
          删除
        </ElButton>
      </template>
    </Table>
  </ContentWrap>

  <Dialog v-model="dialogVisible" :title="dialogTitle">
    <Edit
      v-if="actionType == 'edit' || actionType == 'add'"
      ref="editRef"
      :form-schema="allSchemas.formSchema"
      :current-row="tableObject.currentRow"
    />

    <See
      v-if="actionType == 'see'"
      :detail-schema="allSchemas.detailSchema"
      :current-row="tableObject.currentRow"
    />

    <template #footer>
      <ElButton v-if="actionType !== 'detail'" type="primary" :loading="loading" @click="save()">
        {{ t('exampleDemo.save') }}
      </ElButton>
      <ElButton @click="dialogVisible = false">{{ t('dialogDemo.close') }}</ElButton>
    </template>
  </Dialog>
</template>
